using Game500.Client.Src.Logic;
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Graphics;

namespace Game500.Client.Src
{
  public class Renderer
  {
    private readonly Camera2D myCamera;
    private readonly SpriteFont myFont;
    private readonly SpriteBatch mySpriteBatch;

    public Renderer(SpriteBatch spriteBatch, Camera2D camera, SpriteFont font)
    {
      mySpriteBatch = spriteBatch;
      myCamera = camera;
      myFont = font;
    }

    public SpriteFont Font
    {
      get { return myFont; }
    }

    public Vector2 DrawString(string text, Vector2 position, Color color)
    {
      Vector2 transformedPosition = myCamera.ConvertToScreenCoords(position.X, position.Y);
      mySpriteBatch.DrawString(myFont, text, transformedPosition, color);
      return Font.MeasureString(text);
    }

    public Camera2D Camera
    {
      get { return myCamera; }
    }

    public SpriteBatch BatchSprite
    {
      get { return mySpriteBatch; }
    }


    public void BeginFrame()
    {
      mySpriteBatch.Begin(SpriteSortMode.BackToFront, BlendState.AlphaBlend);
    }

    public void EndFrame()
    {
      mySpriteBatch.End();
    }

    public void RenderSprite(Sprite sprite)
    {
      RenderSprite(sprite.Texture, sprite.Position, sprite.Origin, sprite.Scale, rotation: sprite.Rotation);
    }

    public void RenderSprite(Texture2D texture, Vector3 position, Vector2 origin, Vector2 scale, Color? tintColor = null, float rotation = 0, Rectangle? sourceRect = null)
    {
      if (tintColor == null) tintColor = Color.White;
      var absOrigin = new Vector2(origin.X * texture.Width, origin.Y * texture.Height);

      SpriteEffects effects = SpriteEffects.None;
      if (scale.X < 0)
      {
        effects |= SpriteEffects.FlipHorizontally;
        scale.X = -scale.X;
      }
      if (scale.Y < 0)
      {
        effects |= SpriteEffects.FlipVertically;
        scale.Y = -scale.Y;
      }

      Vector2 transformedPosition = myCamera.ConvertToScreenCoords(position.X, position.Y);

      mySpriteBatch.Draw(texture, transformedPosition, sourceRect, tintColor.Value, rotation, absOrigin, scale, effects, position.Z);
    }
  }
}